<?php
/**
 * @author dinglin
 * 每日9：40后开始执行，且只执行一次
 * 更新当日早上打卡记录，9：40之前
 * 产生迟到或上午缺勤状态
 * 对当日的9：40之前“提交”或“批准“或”驳回“或“撤销”的请假，出差，公出不做统计范围
 *
 * 如果“已批准“，无打卡仍为正常。其它除外。
 * */
apf_require_class('Oa_Job_Attendance_Abstract');
apf_require_class('Const_LeaveType');
apf_require_class('Tools_Tools');
class Oa_Job_Attendance_UpdateAmRecord extends Oa_Job_Attendance_Abstract {

    /** 考勤系统读 **/
    private $readdb = "attendance_slave";
    /** 考勤系统写 **/
    private $writedb = "attendance_master";
    //今天
    private $date = '';
    //sql
    private $sql = '';
    //上班时间
    private $am_start_work = 900;
    private $am_late_time = 910;
    private $am_absenteeism_time = 930;
    private $am_end_work = 1200;
    /*
    private $pm_start_work = 1400;
    private $pm_late_time = 1410;
    private $pm_absenteeism_time = 1430;
    private $pm_leave_early_time = 1730;
    private $pm_end_work = 1800;
    */
    public function run($param){
        $this->date = date('Ymd');
        if($param['date']){
            $this->date = intval(date('Ymd',strtotime($param['date'])));
        }
        $now_time = intval(date('Hi'));
        if($param['time']){
            $now_time = intval(date('Hi',strtotime($param['time'])));
        }
        $this->log("开始更新".date('Y-m-d',strtotime( $this->date))."日早上打卡记录...");
        //特殊工作日
        $special_day_time = Tools_Tools::get_instance()->special_leave_time();
        //特殊工作日
        $today = date('Y-m-d',strtotime( $this->date));
        if(isset($special_day_time[$today])){
            $today_start_time = intval(date('Hi',strtotime($special_day_time[$today]['start_time'])));
            if($today_start_time > $this->am_start_work && $today_start_time > $now_time ){
                $this->log("更新".date('Y-m-d',strtotime( $this->date))."日早上打卡记录 : 未到上班时间，不需更新");
                return ;
            }
            if($today_start_time > $this->am_start_work && $today_start_time <= $now_time){
                $this->am_start_work = $today_start_time;
                $this->am_late_time = $today_start_time;
                $this->am_absenteeism_time = $today_start_time;
            }
        }
        //获取当日9：40之前的打卡记录
        $all_am_records = $this->_get_all_am_records();
        $all_am_records = $this->_do_data_to_index_id( $all_am_records );
        //所有员工初始记录、
        $all_init_records = $this->_get_all_user_day_record();
        //所有销售和非上海员工
        $sales_and_not_shanghai = $this->_get_sale_and_not_in_shanghai();

        foreach($all_init_records as $init_record){
            //销售 非上海
            if(in_array($init_record['user_id'], $sales_and_not_shanghai)){
                continue;
            }
            //如果有请假或公出或出差的批准
            if($init_record['am_leave_status'] == Const_LeaveType::LEAVE_STATUS_PASS){
                continue;
            }

            $record = array();

            //无打卡记录
            if(!isset($all_am_records[$init_record['user_id']])){
                $record['user_id'] = $init_record['user_id'];
                $record['days']      = 0.5;
                $record['am_status'] = Const_LeaveType::KQ_AM_STATUS_3;//上午缺勤
                $record['is_later']  =  0 ;
            }else{
                $am_record = $all_am_records[$init_record['user_id']];
                $am_record['start_work'] = intval($am_record['start_work']);
                //上午缺勤
                if(!$am_record['start_work'] || $am_record['start_work'] > $this->am_absenteeism_time){
                    $record['user_id'] = $init_record['user_id'];
                    $record['days']      = 0.5;
                    $record['am_status'] = Const_LeaveType::KQ_AM_STATUS_3;//上午缺勤
                    $record['is_later']  =  0 ;
                }elseif($am_record['start_work'] > $this->am_late_time && $am_record['start_work'] <= $this->am_absenteeism_time){
                    //迟到
                    $record['user_id'] = $init_record['user_id'];
                    $record['days']      = 0 ;
                    $record['am_status'] = Const_LeaveType::KQ_AM_STATUS_1;//迟到
                    $record['is_later']  =  1 ;
                }elseif($am_record['start_work'] <= $this->am_late_time && ($init_record['am_status'] == Const_LeaveType::KQ_AM_STATUS_3 || $init_record['am_status'] == Const_LeaveType::KQ_AM_STATUS_1)){//打卡机器故障，补跑
                    $record['user_id'] = $init_record['user_id'];
                    $record['days']      = 0 ;
                    $record['am_status'] = Const_LeaveType::KQ_AM_STATUS_5;//正常
                    $record['is_later']  =  0 ;
                }
            }
            //更新数据
            $this->_update_user_day_record($record);
        }
        //新入职员工记录
        //$this->_inset_new_colleague_day_record( $all_init_records , $all_am_records );
        unset($all_am_records);
        unset($all_init_records);
        unset($sales_and_not_shanghai);
        $this->log("更新".date('Y-m-d',strtotime( $this->date))."日早上打卡记录完毕");
    }
    /**
     * 获取当日9：40之前的打卡记录
     */
    private function _get_all_am_records(){
        $this->sql = "SELECT start_work,user_id FROM access_day_record WHERE access_date = ".$this->date;
        return $this->get_db_rows($this->sql,$this->writedb,array());
    }
    /**
     * 获取所有用户初始打卡记录
     * @return multitype:
     */
    private function _get_all_user_day_record(){
        $this->sql = "SELECT user_id,am_type,am_status,am_leave_status FROM user_day_status WHERE dateline={$this->date}";
        return $this->get_db_rows($this->sql,$this->writedb,array());
    }
    /**
     * 更新打卡“异”常状态到日常打卡记录表
     * @param unknown_type $data
     */
    private function _update_user_day_record( $data ){
        //data为空，表示打卡正常
        if(empty($data)){
            return;
        }
        $data['days']      = isset($data['days']) ? $data['days'] : 0;
        $data['am_status'] = isset($data['am_status']) ? $data['am_status'] : Const_LeaveType::KQ_AM_STATUS_5;
        $data['is_later']  = isset($data['is_later']) ? $data['is_later'] : 0;
        $this->sql = "UPDATE user_day_status SET days={$data['days']},am_status={$data['am_status']},is_later={$data['is_later']} WHERE user_id={$data['user_id']} and dateline={$this->date}";
        $this->execute( $this->sql,array(), $this->writedb);
        $this->log("更新date:{$this->date}日的user_id:{$data['user_id']}早上打卡记录完毕");
        unset($data);
    }
    /**
     * 数据转换为以user_id为索引
     * @param unknown_type $data
     */
    private function _do_data_to_index_id(&$data){
        $result = array();
        foreach($data as $one){
            $result[$one['user_id']] = $one;
        }
        unset($data);
        return $result;
    }
    /**
     * 获取所有销售人员和非上海人员
     */
    private function _get_sale_and_not_in_shanghai(){
        $result = array();
        $last_timetamp=strtotime(date('Y-m-d'));
        $sale_department = APF::get_instance()->get_config('sale_department');
        $city_card = APF::get_instance()->get_config('city_card');
        $city_names = array_values($city_card);

        $start = 0;
        $limit = 100;
        while(true) {
            $sql = "SELECT user_id,department_name,department_id,city_name,enter_date FROM user_info WHERE user_id > {$start} AND job_status='在职' ORDER BY user_id asc limit {$limit}";
            $tmp = $this->get_db_rows($sql,$this->writedb,array());
            if(empty($tmp)) {
                $this->log("取完所有用户数据!");
                break;
            }
            $count = count($tmp);
            $start = $tmp[$count - 1]['user_id'];
            $result = array_merge($result,$tmp);
        }
        //过滤未入职员工
        $res = array();
        foreach ($result as $index => $value){
            if(in_array($value['city_name'],$city_names)){//非打卡城市
                continue;
            }
            $enter_time = strtotime($value['enter_date']);
            if($enter_time > $last_timetamp){
                continue;
            }
            if(empty($sale_department[$value['department_id']])){
                continue;
            }
            $res[$value['user_id']] = $value['user_id'];
        }
        return $res;
    }
}